package cn.edu.sjtu.spinning.global;

import cn.edu.sjtu.spinning.domain.Task;
import cn.edu.sjtu.spinning.enums.DeviceStatus;
import cn.edu.sjtu.spinning.enums.TaskStatus;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
@Data
@Slf4j
public class ExecuteTask {
  private Task currentTask;
  private DeviceStatus deviceStatus = DeviceStatus.READY;

  @Value("${spinning.executeTime}")
  private long executeTime;

  @Value(("${spinning.doneTime}"))
  private long doneTime;

  private Map<String, Task> taskMap = new ConcurrentHashMap<>();

  private void beginTask(Task task) {
    this.currentTask = task;
    // 让设备执行
    this.deviceStatus = DeviceStatus.BUSY;
    String key = task.getProcessId().concat(task.getTaskId());
    // 任务开始执行
    Task cur = taskMap.get(key);
    cur.setStatus(TaskStatus.EXECUTING);
    cur.setStartTime(new Date());
  }

  private void finishTask() {
    // 设备状态转为空闲
    this.deviceStatus = DeviceStatus.IDLE;
    // 任务状态变为done
    currentTask.setStatus(TaskStatus.DONE);
    currentTask.setEndTime(new Date());
    this.currentTask = null;
  }

  private void readyTask() {
    this.deviceStatus = DeviceStatus.READY;
  }

  @Async
  public void executeTask(Task task) {
    beginTask(task);
    try {
      Thread.sleep(executeTime);
    } catch (InterruptedException e) {
      log.error("线程休眠中断，历史执行任务有: {}", taskMap);
    }
    String finishedTaskId = task.getTaskId();
    finishTask();
    try {
      Thread.sleep(doneTime);
    } catch (InterruptedException e) {
      log.error("线程休眠中断，历史执行任务有: {}", taskMap);
    }
    readyTask();
    log.info("当前任务: {}，已完成", finishedTaskId);
  }
}
